﻿@page "/favorite"
@using DailyPoetryH.Library.Models
@inject IFavoriteStorage _favoriteStorage
@inject IPoetryStorage _poetryStorage
@inject INavigationService _navigationService

@foreach (var poetryFavorite in _poetryFavorites) {
    <div @onclick="() => OnClick(poetryFavorite.Poetry)">
        <Card>
            <BodyTemplate>
                <span style="font-weight: bold; color: #0078d4">@poetryFavorite.Poetry.Name</span>
                <div class="shim-2xs"></div>
                @poetryFavorite.Poetry.Dynasty @poetryFavorite.Poetry.Author
                <div class="shim-2xs"></div>
                @poetryFavorite.Poetry.Content.Substring(0, poetryFavorite.Poetry.Content.IndexOf("。"))……
            </BodyTemplate>
        </Card>
    </div>
    <div class="shim-xl"></div>
}
<div id="observerTarget">
    @_status
</div>
<div class="shim-xl"></div>

@code {
    private List<PoetryFavorite> _poetryFavorites = new();

    private string _status = String.Empty;

        public const string Loading = "正在载入";

        public const string NoMoreResult = "没有更多结果";

    protected override async Task OnAfterRenderAsync(bool firstRender) {
        if (!firstRender) {
            return;
        }

        _status = Loading;
        _poetryFavorites.Clear();
        StateHasChanged();

        var favorites = await _favoriteStorage.GetFavoritesAsync();
        var tasks = favorites.Select(async favorite => {
            var poetry = await _poetryStorage.GetPoetryAsync(favorite.PoetryId);
            return new PoetryFavorite { Poetry = poetry, Favorite = favorite};
        });
        var poetryFavorites = await Task.WhenAll(tasks);
        _poetryFavorites.AddRange(poetryFavorites);

        _status = NoMoreResult;
        StateHasChanged();
    }

    public async Task<PoetryFavorite> DoAsync(Models.Favorite favorite) {
        var poetry = await _poetryStorage.GetPoetryAsync(favorite.PoetryId);
        return new PoetryFavorite { Poetry = poetry, Favorite = favorite};
    }

    private void OnClick(Poetry poetry) => _navigationService.NavigateTo($"{NavigationServiceConstants.DetailPage}/{poetry.Id}");

    public class PoetryFavorite {
        public Poetry Poetry { get; set; }

        public Models.Favorite Favorite { get; set; }
    }

}